/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package modelo;

import clases.Caja;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 *
 * @author Edder
 */
public class MdlCaja implements Modelo<Caja>{

    /**
     * 
     * @param caja
     * @param cnx
     * @throws SQLException 
     */
    @Override
    public void insert(Caja caja, Conexion cnx) throws SQLException {
        String sql = "INSERT INTO caja(nombre) "
                + "VALUES ('"+ caja.getNombre() +"');";
        cnx.ejecutar(sql);
    }

    /**
     * 
     * @param cnx
     * @return
     * @throws SQLException 
     */
    @Override
    public int getLastId(Conexion cnx) throws SQLException {
        String sql = "SELECT max(idCaja) FROM caja";
        ResultSet rs = cnx.consultar(sql);
        if (rs.next()) {
            return rs.getInt(1);
        }
        return -1;
    }

    /**
     * 
     * @param caja
     * @param cnx
     * @throws SQLException 
     */
    @Override
    public void update(Caja caja, Conexion cnx) throws SQLException {
        String sql = "UPDATE caja SET "
                + "nombre = '" + caja.getNombre() +"' "
                + "WHERE idCaja = " + caja.getIdCaja() + ";";
        cnx.ejecutar(sql);
    }

    /**
     * 
     * @param query
     * @param cnx
     * @return
     * @throws SQLException 
     */
    @Override
    public ArrayList<Caja> get(String query, Conexion cnx) throws SQLException {
        ResultSet rs = cnx.consultar(query);
        ArrayList<Caja> cajas;
        cajas = new ArrayList<>();
        while(rs.next()){
            cajas.add(new Caja(rs.getInt(1), rs.getString(2)));
        }
        return cajas;
    }

    /**
     * 
     * @param idCaja
     * @param cnx
     * @return
     * @throws SQLException 
     */
    @Override
    public Caja get(int idCaja, Conexion cnx) throws SQLException {
        String sql = "SELECT * FROM caja WHERE idCaja LIKE " + idCaja;
        ResultSet rs = cnx.consultar(sql);
        Caja caja = null;
        
        if (rs.next()) {
            caja = new Caja(rs.getInt(1), rs.getString(2));
        }
        
        return caja;
    }
    
}
